package Test;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/4/4
 * \* Time: 20:35
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */

class MyBlockingQueue{
    //保存数据本体
    private int[] data = new int[1000];
    //有效元素个数
    private int size = 0;
    //队首下标
    private int head = 0;
    //队尾下标
    private int tail = 0;
    //专门锁对象
    private Object locker = new Object();

    //入队列
    public void put(int value) throws InterruptedException {
        synchronized (locker){
            if(size == data.length){
                //队列满了，暂时先直接返回
                //return
                locker.wait();
            }
            //把新的元素放到tail的位置
            data[tail] = value;
            tail++;
            //处理tail到达数组末尾的情况
            if(tail >= data.length){
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }

    //出队列
    public Integer take() throws InterruptedException {
        synchronized (locker){
            if(size == 0 ){
                locker.wait();
            }
            int ret = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}

public class Demo4 {
    private static MyBlockingQueue queue = new MyBlockingQueue();
    public static void main(String[] args) {
        Thread producer = new Thread(()->{
           int num = 0;
           while (true){

               try {
                   System.out.println("生产了:" + num);
                   queue.put(num);
                   num++;
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        producer.start();

        Thread customer = new Thread(()->{
            while (true){
                try {
                    int num = queue.take();
                    System.out.println("消费了："+num);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }
}
